package com.wu.webflux2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity.AuthorizeExchangeSpec;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;

import reactor.core.publisher.Mono;

@EnableWebFluxSecurity
public class WebFluxConfig {

	@Bean
	public MapReactiveUserDetailsService userDetailsService() {
		// 自定义一个用户
		UserDetails user = User.withDefaultPasswordEncoder().username("wu").password("123").roles("ADMIN")
				.authorities("ROLE_USER").build();
		return new MapReactiveUserDetailsService(user);
	}

	@Bean
	public SecurityWebFilterChain springSecurityFilterChain2(ServerHttpSecurity http) {
		ServerHttpSecurity build = http.formLogin().loginPage("/index")
				.requiresAuthenticationMatcher(
						ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/account/login"))
				.authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/hello")).and()
				.authorizeExchange().pathMatchers("/js/**", "/actuator/**", "/index", "/logout").permitAll()
				.pathMatchers("/hello").hasAnyAuthority("ROLE_USER").pathMatchers("/**").authenticated().and().logout().and()
				.csrf().disable();
		return build.build();
	}
}
